﻿using RPAVIEW.views.EditPage;
using SUNRPA.CONTROLS.IMPL.util;
using System;
using System.IO;
using System.Threading.Tasks;
using System.Windows;

namespace RPAVIEW.views.OtherPages {
    /// <summary>
    /// DownLoader.xaml 的交互逻辑
    /// </summary>
    public partial class DownLoader:Window {
        public static LogUtil logger = new LogUtil(typeof(DownLoader));
        public Stream downloadStream;
        public bool complete = false;
        public string downloadPath;
        public DownLoader(Stream stream, string path) {
            this.downloadStream = stream;
            this.downloadPath = path;
            InitializeComponent();
        }

        //取消下载
        private void Cancel(object sender, RoutedEventArgs e) {
            this.Close();
        }

        private void BeginDownLoad(object sender, RoutedEventArgs e) {
            Task.Run(() => {
                try { 
                    using(BufferedStream bs = new BufferedStream(downloadStream)) { 
                        byte[] lengthBtyes = new byte[4];
                        bs.Read(lengthBtyes, 0, lengthBtyes.Length);
                        long totalLength = BitConverter.ToInt32(lengthBtyes, 0);
                        double downLength = 0;
                        byte[] buffer = new byte[102400];
                        FileStream fs = File.Create(downloadPath);
                        int len = bs.Read(buffer, 0, buffer.Length);
                        while(len > 0) { 
                            downLength += len;
                            double process = Math.Floor((downLength / totalLength) * 100);
                            progress.Dispatcher.Invoke(new Action(() => {
                                progress.Text = process.ToString();
                            }));
                            fs.Write(buffer, 0, len);
                            len = bs.Read(buffer, 0, buffer.Length);
                        }
                        fs.Flush();
                        fs.Close();
                        this.complete = true;
                    }
                }catch (Exception ex) { 
                    logger.Error("下载出错", ex, null);
                }finally { 
                    this.Dispatcher.Invoke(new Action(() => { 
                        this.Close();
                    }));
                }
            });
        }
    }
}
